<template>
    <div class="app-container">
        <el-form  :inline="true" :model="queryParams" >
            <el-form-item label="">
                <el-cascader :options="options" :props="props" v-model="queryParams.outPortCode" :show-all-levels="false" clearable></el-cascader>
            </el-form-item>
            <el-form-item>
                <tabDate :tabs="dateTypeTabs" ref="tabDateRef" notFormat @btnTabChange="btnTabChange($event)" />
                <!-- <el-radio-group v-model="dateType" size="small" @input="btnTabChange">
                    <el-radio-button label="日"></el-radio-button>
                    <el-radio-button label="周" ></el-radio-button>
                    <el-radio-button label="月" ></el-radio-button>
                    <el-radio-button label="季度"></el-radio-button>
                    <el-radio-button label="半年"></el-radio-button>
                    <el-radio-button label="年"></el-radio-button>
                </el-radio-group> -->
            </el-form-item>
            <!-- <el-form-item>
                <el-date-picker 
                    v-model="queryParams.date" 
                    type="date"
                    placeholder="选择日期" 
                    value-format="yyyy-MM-dd"
                    format="yyyy-MM-dd">
                </el-date-picker>
            </el-form-item> -->
            <el-form-item>
                <el-button type="primary" @click="queryData">查询</el-button>
                <el-button @click="exportData">导出</el-button>
            </el-form-item>
        </el-form>
        <div class="mb-20">
            <div class="t-center f-18 mb-10">{{tableTitle}}</div>
            <div class="d-flex a-center f-12 c-666 mb-5">
                <div style="width: 50%;">污染源名称：{{reportData.PolluteName}}</div>
                <div style="width: 50%;">排放口名称：{{reportData.outportName}}</div>
            </div>
            <div class="d-flex a-center f-12 c-666">
                <div style="width: 50%;">开始时间：{{reportData.beginTime}}</div>
                <div style="width: 50%;">结束时间：{{reportData.endTime}}</div>
            </div>
        </div>
        <el-table :data="reportData.list" style="width: 100%" border v-loading="loading">
            <el-table-column prop="monitorTime" label="监测时间"></el-table-column>
            <el-table-column v-for="item  in reportData.column" :prop="item.prop" :label="reportData.columns[item.prop]" width="width"></el-table-column>
        </el-table>
    </div>
</template>
<script>
    import {polluteTree,reportAnalyseDay,reportAnalyseWeek,reportAnalyseMonth,reportAnalyseQuarter,reportAnalyseSemiannual,reportAnalyseYear} from './api'
    import {reportAnalyseDayExport,reportAnalyseWeekExport,reportAnalyseMonthExport,reportAnalyseQuarterExport,reportAnalyseSemiannualExport,reportAnalyseYearExport} from './api'
    import tabDate from '@/components/viewComponents/tabDate/tabDate.vue'
   export default {
        components:{
            tabDate
        },  
        data() {
            return {
                options:[],
                props:{
                    value: 'id',
                    label: 'name',
                    // multiple :true,
                    expandTrigger:'hover'
                },
                queryParams: {
                    outPortCode:'',
                    date: new Date(),
                },
                beginTime: '',
                endTime: '',
                dateType: '年',
                list: [],
                total: 0,
                pageNum: 1,
                pageSize: 10,
                loading: false,
                dateTypeTabs:[
                    {value:'date',name:'日'},
                    {value:'week',name:'周'},
                    {value:'month',name:'月'},
                    {value:'quarter',name:'季度'},
                    {value:'byear',name:'半年'},
                    {value:'year',name:'年'},
                ],
                reportFnMap:{
                    "日":reportAnalyseDay,
                    "周":reportAnalyseWeek,
                    "月":reportAnalyseMonth,
                    "季度":reportAnalyseQuarter,
                    "半年":reportAnalyseSemiannual,
                    "年":reportAnalyseYear,
                },
                tableTitle:'',
                reportData:{},
                exportFnMap:{
                    "日":reportAnalyseDayExport,
                    "周":reportAnalyseWeekExport,
                    "月":reportAnalyseMonthExport,
                    "季度":reportAnalyseQuarterExport,
                    "半年":reportAnalyseSemiannualExport,
                    "年":reportAnalyseYearExport,
                },
            }
        },
        computed:{
            queryTime(){
                let dateRange = this.$refs.tabDateRef.getDateValue();
                return dateRange;
                // let beginTime,endTime;
                // if(this.dateType == '日'){
                //     beginTime = $moment(this.queryParams.date).format('{yyyy}-{mm}-{dd}');
                //     endTime = $moment(this.queryParams.date).format('{yyyy}-{mm}-{dd}');
                // } else if(this.dateType == '周'){
                //     beginTime = $moment(this.queryParams.date).startOf('week').format('{yyyy}-{mm}-{dd}');
                //     endTime = $moment(this.queryParams.date).endOf('week').format('{yyyy}-{mm}-{dd}');
                // } else if(this.dateType == '月'){
                //     beginTime = $moment(this.queryParams.date).startOf('month').format('{yyyy}-{mm}-{dd}');
                //     endTime = $moment(this.queryParams.date).endOf('month').format('{yyyy}-{mm}-{dd}');
                // } else if(this.dateType == '季度'){
                //     let month = $moment(this.queryParams.date).format('{mm}');
                //     let jd = [['01','03'],['04','06'],['07','09'],[10,12]];
                //     let jdIndex = jd.findIndex(item => item[0]<=month && month<=item[1]);
                //     let beginStr = `${$moment(this.queryParams.date).format('{yyyy}')}-${jd[jdIndex][0]}-01`;
                //     beginTime = $moment(beginStr).format('{yyyy}-{mm}-{dd}');
                //     endTime = $moment(beginTime).offset('month',2).endOf('month').format('{yyyy}-{mm}-{dd}');
                // } else if(this.dateType == '半年'){
                //     let month = $moment(this.queryParams.date).format('{mm}');
                //     let jd = [['01','06'],['07',12]];
                //     let jdIndex = jd.findIndex(item => item[0]<month && month<=item[1]);
                //     beginTime = `${$moment(this.queryParams.date).format('{yyyy}')}-${jd[jdIndex][0]}-01`;
                //     endTime = $moment(beginTime).offset('month',5).endOf('month').format('{yyyy}-{mm}-{dd}');
                // } else if(this.dateType == '年'){
                //     let year = $moment(this.queryParams.date).format('{yyyy}');
                //     beginTime = `${year}-01-01`;
                //     endTime = `${year}-12-31`
                // }
                
                // return [beginTime, endTime];
            }
            
        },
        created(){
            this.beginTime = $moment('2025-01-01').format('{yyyy}-{mm}-{dd}');
            this.endTime = $moment('2025-12-31').format('{yyyy}-{mm}-{dd}');
            this.createdFn()
        },
        methods: {
            async createdFn(){
                await this.getpolluteTree();
                this.getList()
            },
            async getpolluteTree(){
                let res = await polluteTree();
                if(res.code == '200'){
                    this.options = res.data;
                    this.queryParams.outPortCode = this.getTreeFirstId(res.data)
                }
            },
            getTreeFirstId(list) { 
                let item = list[0];
                let ids = [];
                if(item) {
                    ids.push(item.id)
                    if(item.children && item.children.length > 0){
                        let _ids =  this.getTreeFirstId(item.children);
                        ids = [...ids, ..._ids];
                    }
                    return ids;
                } else {
                    return []
                }
            },
            async getList(){
                let outPortCode = this.queryParams.outPortCode[this.queryParams.outPortCode.length-1];
                let apiParams = {
                    outPortCode,
                    beginTime: this.queryTime[0],
                    endTime: this.queryTime[1],
                }
                
                let apiFn = this.reportFnMap[this.dateType];
                this.loading = true;
                let res =  await  apiFn(apiParams);
                this.tableTitle = `监控数据${this.dateType}报表`
                if(res.code == '200'){
                    if(res.data.dataList) {
                        res.data.list = res.data.dataList;
                    }
                    if(res.data.columnTitle){
                        res.data.columns = res.data.columnTitle;
                    }
                    this.reportData = res.data;
                    if(this.reportData.list.length > 0) {
                        let avgItem = {monitorTime:'平均值',...res.data.avg};
                        let minItem = {monitorTime:'最小值',...res.data.min};
                        let maxItem = {monitorTime:'最大值',...res.data.max};
                        let sunItem = {monitorTime:'合计',...res.data.sum};
                        this.reportData.list.push(avgItem);
                        this.reportData.list.push(minItem);
                        this.reportData.list.push(maxItem);
                        this.reportData.list.push(sunItem);
                    }
                }
                this.loading = false;

            },
            btnTabChange(type){
                let item = this.dateTypeTabs.find(item => item.value == type)
                this.dateType = item.name;
                this.getList();
            },

            queryData() {
                this.getList()
            },
            exportData() {
                let outPortCode = this.queryParams.outPortCode[this.queryParams.outPortCode.length-1];
                let apiParams = {
                    outPortCode,
                    beginTime: this.queryTime[0],
                    endTime: this.queryTime[1],
                }
                let apiFn = this.exportFnMap[this.dateType];
                let url =  apiFn(apiParams);
                const filePath = `${url}`;
                
                // 创建下载链接
                const link = document.createElement('a');
                link.href = filePath;
                link.download = this.tableTitle;
                link.style.display = 'none';
                
                // 添加到页面并触发下载
                document.body.appendChild(link);
                link.click();
                // 清理
                document.body.removeChild(link);
            },
        }
    }
</script>